package com.davidx.tool.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.davidx.tool.enums.ErrorCodeEnum;
import com.davidx.tool.wrapper.WrapMapper;
import com.davidx.tool.wrapper.Wrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Davidx
 */
@Slf4j
@WebFilter(urlPatterns = {"/api/*"}, filterName = "TokenFilter")
public class TokenFilter implements Filter {

    private List<String> ipList=new ArrayList<>();
    private List<String> tokenList=new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) {
        ipList.add("192.168.1.133");
        ipList.add("192.168.1.132");
        ipList.add("47.105.168.228");
        ipList.add("47.93.23.15");
        tokenList.add("bb797fed1c2759c2940fdd06423fab1b");
        tokenList.add("9606d41dcef355749e8d591b859df47b");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getParameter("token");
        String clientIP = HttpUtil.getClientIP(req);
        Wrapper<Object> error=null;
        if (authIP(clientIP)) {
            if (authToken(token)) {
                filterChain.doFilter(request, response);
            }else{
                 error = WrapMapper.wrap(ErrorCodeEnum.GL99990003.code(),ErrorCodeEnum.GL99990003.msg());
            }
        }else{
            error = WrapMapper.wrap(ErrorCodeEnum.GL99990004.code(),ErrorCodeEnum.GL99990004.msg());
        }
        if(ObjectUtil.isNotNull(error)){
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json; charset=utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String writeValueAsString = objectMapper.writeValueAsString(error);
            response.getWriter().write(writeValueAsString);
        }
    }

    private boolean authIP(String ip) {
        return CollectionUtils.contains(ipList.iterator(),ip);
    }

    private boolean authToken(String token) {
        return CollectionUtils.contains(tokenList.iterator(),token);

    }

    @Override
    public void destroy() {
    }
}
